package com.xiefengf.elasticsearch.elasticsearch_client;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.junit.jupiter.api.Test;

import java.io.IOException;

/**
 * @author xiefengf
 * @version 1.0
 * @date 2024/3/20 21:53
 *
 * 索引（index）增删改查
 */
public class Index {

    /**
     * 创建ES客户端
     * @return
     */
    public RestHighLevelClient createClient(){
        return new RestHighLevelClient(RestClient.builder(new HttpHost("124.220.215.81",9200,"http")));
    }

    /**
     * 关闭ES客户端
     * @param client
     */
    public void closeClient(RestHighLevelClient client){
        try {
            client.close();
        } catch (IOException e) {
            System.out.println("关闭客户端失败");
        }
    }

    /**
     * 根据索引名称查询索引
     */
    @Test
    public void getIndexByName() throws IOException {
        // 创建客户端
        RestHighLevelClient client = createClient();
        // 查询索引
        GetIndexResponse response = client.indices().get(new GetIndexRequest("user"), RequestOptions.DEFAULT);
        // 输出结果
        System.out.println(response.getAliases());
        System.out.println(response.getMappings());
        System.out.println(response.getMappings());
        System.out.println(response.getIndices()[0]);
        // 关闭客户端
        closeClient(client);
    }

    /**
     * 创建索引
     */
    @Test
    public void saveIndex() throws IOException {
        // 创建客户端
        RestHighLevelClient client = createClient();
        // 创建索引
        CreateIndexResponse response = client.indices().create(new CreateIndexRequest("user"), RequestOptions.DEFAULT);
        // 输出结果
        System.out.println("执行结果："+response.isAcknowledged());
        // 关闭客户端
        closeClient(client);
    }

    /**
     * 删除索引
     */
    @Test
    public void deleteIndex() throws IOException {
        // 创建客户端
        RestHighLevelClient client = createClient();
        // 删除索引
        AcknowledgedResponse response = client.indices().delete(new DeleteIndexRequest("user"), RequestOptions.DEFAULT);
        // 输出结果
        System.out.println(response.isAcknowledged());
        // 关闭客户端
        closeClient(client);
    }

}
